package com.wujilee.wujileenetty.demos.web.netty.heima;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author liwuji
 * @date 2024/8/6
 * @desc
 **/
public class Boss {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        Worker worker = new Worker();
        worker.setName("worker0");
        while (true) {
            // 无论是阻塞还是非阻塞模式：该方法都是阻塞的
            selector.select();
            selector.selectedKeys().stream().forEach(selectionKey -> {
                try {
                    if (selectionKey.isAcceptable()) {
                        System.out.println("主线程接收到连接请求");
                        ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                        // 阻塞模式下该方法回导致阻塞
                        SocketChannel socketChannel = channel.accept();
                        socketChannel.configureBlocking(false);
                        // 注册
//                        socketChannel.register(selector, SelectionKey.OP_READ);
                        worker.register(socketChannel);
                    }

                } catch (Exception e) {

                }
            });
        }
    }
}

